<template>

  <div>
    <div>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/welcome3' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: $route.path }">{{ $route.meta.title }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
<!--    <div>-->
<!--      <el-select v-model="value" placeholder="请选择要搜索的字段" size="mini">-->
<!--        <el-option-->
<!--            v-for="item in options"-->
<!--            :key="item.value"-->
<!--            :label="item.label"-->
<!--            :value="item.value">-->
<!--        </el-option>-->
<!--      </el-select>-->
<!--      &lt;!&ndash;  搜索&ndash;&gt;-->
<!--      <el-input v-model="search" placeholder="请输入要查询的字段的值" style="width: 20%;margin-left: 10px" size="mini"></el-input>-->
<!--      <el-button type="primary" style="margin-top: 10px;margin-left: 10px" @click="ShowSearch()" icon="el-icon-search" size="mini">查询</el-button>-->
<!--    </div>-->
    <div style="margin-top: 10px;margin-bottom: 10px">
      <el-button
          size="mini"
          type="primary"
          class="handle-del mr10"
          style="width: 160px"
          @click="ShowAllExpert()"
      >展示所有数据</el-button>
      <el-button
          size="mini"
          type="primary"
          style="width: 160px"
          class="handle-del mr10"
          @click="ExpertAdd()"
          icon="el-icon-circle-plus-outline"
      >添加专家账号</el-button>
      <el-button
          size="mini"
          type="primary"
          style="width: 160px"
          class="handle-del mr10"
          @click="Export()"
          icon="el-icon-download"
      >导出</el-button>
      <el-button
          type="primary"
          style="width: 160px"
          class="handle-del mr10"
          @click="randomPassword"
          icon="el-icon-edit"
          size="mini"
      >生成密码</el-button>
      <i class="el-icon-question" style="color: red">点击表格最左侧多选框，批量生成随机密码</i>
    </div>
    <el-table
        :row-style="{height:'10px'}"
        :cell-style="{padding:'0px'}"
        size="mini"
        :data=this.tableData
        border
        :header-cell-style="{background:'lightblue',color:'#262626'}"
        @selection-change="handleSelectionChange"
        style="width: 1086px">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          prop="username"
          label="账号"
          align="center"
          width="120">
      </el-table-column>
      <el-table-column
          prop="password"
          label="密码"
          align="center"
          width="120">
      </el-table-column>
      <el-table-column
          prop="realname"
          label="真实姓名"
          align="center"
          width="80">
      </el-table-column>
      <el-table-column
          prop="workplace"
          label="工作单位"
          align="center"
          width="210">
      </el-table-column>
      <el-table-column
          prop="bankaccount"
          label="银行卡号"
          align="center"
          width="150">
      </el-table-column>
      <el-table-column
          prop="banklocation"
          label="开户行"
          align="center"
          width="150">
      </el-table-column>
      <el-table-column
          prop="title"
          label="职称"
          align="center"
          width="100">
      </el-table-column>
      <el-table-column
          label="操作"
          align="center"
          width="100">
        <template slot-scope="scope">
          <el-button @click="edit(scope.row),dialogFormVisible = true" type="text" size="small">修改</el-button>
          <el-button @click="del(scope.row)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-table
        :data=this.tableData1
        border
        hidden
        id="out-table1"
        :header-cell-style="{background:'lightblue',color:'#262626'}"
        style="width: 381px">
      <el-table-column
          prop="username"
          label="账号"
          align="center"
          width="120">
      </el-table-column>
      <el-table-column
          prop="password"
          label="密码"
          align="center"
          width="120">
      </el-table-column>
      <el-table-column
          prop="realname"
          label="真实姓名"
          align="center"
          width="80">
      </el-table-column>
      <el-table-column
          prop="workplace"
          label="工作单位"
          align="center"
          width="210">
      </el-table-column>
      <el-table-column
          prop="bankaccount"
          label="银行卡号"
          align="center"
          width="150">
      </el-table-column>
      <el-table-column
          prop="banklocation"
          label="开户行"
          align="center"
          width="150">
      </el-table-column>
      <el-table-column
          prop="title"
          label="职称"
          align="center"
          width="100">
      </el-table-column>
    </el-table>
    <el-dialog :title=this.modeName :visible.sync="dialogFormVisible" :show-close=false width="950px">
      <hr style="margin-top: -30px;margin-bottom: 10px">
      <el-form :model="ruleForm" :rules="rules" :inline="true" ref="ruleForm" label-width="180px" class="demo-ruleForm">
        <el-form-item label="专家账号" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="专家密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="专家真实姓名" prop="realname">
          <el-input v-model="ruleForm.realname"></el-input>
        </el-form-item>
        <el-form-item label="专家工作单位" prop="workplace">
          <el-input v-model="ruleForm.workplace"></el-input>
        </el-form-item>
        <el-form-item label="专家银行卡号" prop="bankaccount">
          <el-input v-model="ruleForm.bankaccount"></el-input>
        </el-form-item>
        <el-form-item label="专家开户行" prop="banklocation">
          <el-input v-model="ruleForm.banklocation"></el-input>
        </el-form-item>
        <el-form-item label="专家职称" prop="title">
          <el-input v-model="ruleForm.title"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('ruleForm'),allid=''">确定</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
        <el-button @click="dialogFormVisible = false,allid=''">取 消</el-button>
        <!--        <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>-->
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  methods:{
    submitForm(formName) {
      const _this=this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.allid){
          axios.put("http://localhost:8081/expert/update",this.ruleForm).then(function (res){
            if (res.data.msg==="更新成功"){
              _this.$message({
                message: '修改成功！',
                type: 'success'
              });
              //添加成功后页面跳转
              // _this.$router.push('/ExpertList')
              _this.dialogFormVisible=false
              // _this.$router.push('/SchoolHost')
              _this.ShowAllExpert()
            }
            else{
              _this.$message({
                message: '用户名重复！请重新输入',
                type: 'fail'
              });
            }
          })
          }
          else {
            axios.post("http://localhost:8081/expert/save",this.ruleForm).then(function (res){
              // console.log(res.data.msg);
              if (res.data.msg==="添加成功"){
                _this.$message({
                  message: '添加成功！',
                  type: 'success'
                  //添加成功后页面跳转
                });
                // _this.$router.push('/ExpertList')
                _this.dialogFormVisible=false
                // _this.$router.push('/SchoolHost')
               _this.ShowAllExpert()
              }
              else{
                _this.$message({
                  message: '用户名重复！请重新输入',
                  type: 'fail'
                });
              }
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    ShowAllExpert(){
      const _this=this
      axios.get('http://localhost:8081/expert/findAll').then(function (res){
        _this.tableData=res.data
      })
    },
    ShowSearch(){
      const _this=this
      axios.get("http://localhost:8081/expert/search/"+this.value+'/'+this.search).then(function (res){
        _this.tableData=res.data
        _this.search=''
      })
    },

    Export(){
      let tables = document.getElementById("out-table1");
      console.log(tables)
      let table_book = this.$XLSX.utils.table_to_book(tables);
      var table_write = this.$XLSX.write(table_book, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        this.$FileSaver.saveAs(
            new Blob([table_write], { type: "application/octet-stream" }),
            "Expert.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, table_write);
      }
      return table_write;
    },
    ExpertAdd(){
      // this.$router.push("/AddExpert")
      this.dialogFormVisible = true;
      this.modeName='添加专家账户'
      this.ruleForm={}
    },
    edit(row){
      // axios.get("http://localhost:8081/expert/selectone/"+row.id).then((res)=>{
      //   this.ruleForm=res.data
      // })
      this.dialogFormVisible = true
      this.modeName='更新专家账户'
      this.ruleForm=row
      this.allid=row.id
    },
    del(row){
      const d=confirm("确定删除吗？");
      if (d){
        axios.delete('http://localhost:8081/expert/delete/'+row.username).then(()=>{
          alert("删除成功")
          // location.reload();
          this.ShowAllExpert()
        })
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    randomPassword(){
      // console.log(this.multipleSelection)
      if (this.multipleSelection.length!==0) {
        for (let i = 0; i < this.multipleSelection.length; i++) {
          let code = '';
          //设置长度，这里看需求，我这里设置了4
          const codeLength = 8;
          //设置随机字符
          const random = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
          //循环codeLength 我设置的4就是循环4次
          for (let i = 0; i < codeLength; i++) {
            //设置随机数范围,这设置为0 ~ 36
            const index = Math.floor(Math.random() * 9);
            //字符串拼接 将每次随机的字符 进行拼接
            code += random[index];
          }
          //将拼接好的字符串赋值给展示的code
          this.code = code;
          // 将选择的行的密码改成随机密码
          this.multipleSelection[i].password = this.code
          // 换传入数据库的三条字段格式
          axios.put("http://localhost:8081/expert/update", this.multipleSelection[i]).then((res) => {
            if (res.data.msg === "更新成功") {
              this.$message({
                message: '修改成功！',
                type: 'success'
              });
            } else {
              this.$message({
                message: '学校名称重复！请重新输入',
                type: 'fail'
              });
            }
          })
        }
      }

    }

  },
  data(){
    return {
      search:'',
      options: [{
        value: '1',
        label: '管理员账号'
      }, {
        value: '2',
        label: '管理员密码'
      }, ],
      value: '',
      multipleSelection:[],
      ruleForm: {
        // id:'',
        username: '',
        password: '',
        realname:'',
        workplace:'',
        bankaccount:'',
        banklocation:'',
        title:''
      },
      rules: {
        // id: [
        //   { required: true, message: '请填写编号 注意与已存在的编号不要重复', trigger: 'blur' }
        // ],
        username: [
          { required: true, message: '请填写专家账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请填写专家密码', trigger: 'blur' }
        ],
        realname: [
          { required: true, message: '请填写专家真实姓名', trigger: 'blur' }
        ],
        workplace: [
          { required: true, message: '请填写工作单位', trigger: 'blur' }
        ],
        bankaccount: [
          { required: true, message: '请填写银行卡号', trigger: 'blur' }
        ],
        banklocation: [
          { required: true, message: '请填写开户行', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请填写职称', trigger: 'blur' }
        ],

      },
      total:null,
      tableData: null,
      tableData1: null,
      allid:'',
      mode:'',
      modeName:'',
      dataList: [],
      fileList: [],
      query: {"page":0, "size":20, count:0},
      column: [
        {label: "序号", prop: "id", type: "string"},
        {label: "管理员账号", prop: "username", type: "string"},
        {label: "管理员密码", prop: "password", type: "string"},

      ],
      editForm: {},
      dialogTableVisible: false,
      dialogFormVisible: false,
      formLabelWidth: '120px',
      editVisible: false,
      currentIndex: null,
    }
  },
  created() {
      const _this=this
      const a=localStorage.getItem("access-admin")
      if(a){
        // this.admin=JSON.parse(window.localStorage.getItem('access-admin'))
        axios.get('http://localhost:8081/expert/findAll').then(function (res){
          _this.tableData=res.data
          _this.tableData1=res.data
        })
      }
      else{
        this.$alert('未登录','提示',{
          confirmButtonText:'确定'
        }).then((res)=>{
          this.$router.replace({path:'/login'})
        })
      }
  }
}
</script>
